<?php
namespace app\common\model\mobile;
use app\common\model\CommonModel;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Request;
class  Code extends CommonModel{
    protected $pk       = 'code_id';
    protected $insert   = [];
    
    public function sendSms($mobile,$num = '86',$template='1234'){
        $data = $this->get(['mobile'=>$mobile]);
        if(empty($data)){
            $code = IS_ONLINE ?   rand(100000,999999) : '123456';
            $this->save([
                'mobile'=>$mobile,
                'code'  =>$code,
                'code_time' => Request::instance()->time(),
                'err_num' => 0,
            ]);
        }else{
            if($data['code_time'] < Request::instance()->time() - 600){ //10分钟
                $code = IS_ONLINE ?   rand(100000,999999) : '123456';
            }else{
                $code = $data['code'];
            }
            $this->save([
                'code_time' => Request::instance()->time(),
                'code' => $code,
                'err_num' => 0,
            ],['mobile'=>$mobile]);
        }
        //下面发短信的逻辑后面补充
        if(IS_ONLINE){
           AlibabaCloud::accessKeyClient('<accessKeyId>', '<accessSecret>')
                        ->regionId('cn-hangzhou')
                        ->asDefaultClient();

try {
    $result = AlibabaCloud::rpc()
                          ->product('Dysmsapi')
                          // ->scheme('https') // https | http
                          ->version('2017-05-25')
                          ->action('SendSms')
                          ->method('POST')
                          ->host('dysmsapi.aliyuncs.com')
                          ->options([
                                        'query' => [
                                          'RegionId' => "cn-hangzhou",
                                          'PhoneNumbers' => $mobile,
                                          'SignName' => "明志",//签名
                                          'TemplateCode' => $template,//短信模板
                                        ],
                                    ])
                          ->request();
    print_r($result->toArray());
} catch (ClientException $e) {
    echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo $e->getErrorMessage() . PHP_EOL;
}
        return $rsp;
        }
        return true;
    }

}